import 'package:dio/dio.dart';
import 'package:hi_net/core/hi_error.dart';
import 'package:hi_net/core/hi_net_adapter.dart';
import 'package:hi_net/request/h_base_request.dart';

// dio适配器
class DioAdapter extends HiNetAdapter {
  @override
  Future<HiNetResponse<T>> send<T>(HBaseRequest request) async {
    var response, options = Options(headers: request.header); //Options是dio里面的参数
    var error;
    try {
      if (request.httpMethod() == HttpMethod.GET) {
        // 如果是get请求
        response = await Dio().get(request.url(), options: options);
      } else if (request.httpMethod() == HttpMethod.POST) {
        // 如果是post请求--注意有个data参数
        response = await Dio()
            .post(request.url(), data: request.params, options: options);
      } else if (request.httpMethod() == HttpMethod.DELETE) {
        // 如果是delete请求--注意有个data参数
        response = await Dio()
            .delete(request.url(), data: request.params, options: options);
      }
      // 其它的自己加 常用的就上面
    } on DioError catch (e) {
      // 捕获异常
      error = e;
      response = e.response;
    }
    if (error != null) {
      // 抛出HiNetError
      throw HiNetError(response?.statusCode ?? -1, error.toString(),
          data: buildRes(response, request));
    }
    return buildRes(response, request);
  }

// 构建我们的HiNetResponse ---有个疑问 就是 这里的response返回的statusCode和statusMessage是后端定义的可以自己根据业务情况改
  HiNetResponse buildRes(response, HBaseRequest request) {
    return HiNetResponse(
        data: response.data,
        request: request,
        statusCode: response.statusCode,
        statusMessage: response.statusMessage,
        extra: response);
  }
}
